package org.jadelyre.lyre;

import org.jadelyre.Sun;
import org.jadelyre.core.codec.sun.SunPacket;

/**
 * 重连配置
 */
public class ReconnectConfig {
    /**
     * 是否启用重连机制，默认不重连
     */
    private boolean enable;
    /**
     * 重连间隔周期，单位秒
     */
    private int period;
    /**
     * 重连次数，为0或负数代表一直重连
     */
    private int count;

    private Runnable reconnectTask;

    public boolean isEnable() {
        return enable;
    }

    public void setEnable(boolean enable) {
        this.enable = enable;
    }

    public int getPeriod() {
        return period;
    }

    public void setPeriod(int period) {
        this.period = period;
    }

    public int getCount() {
        return count;
    }

    public void setCount(int count) {
        this.count = count;
    }

    public Runnable reconnectTask(LyreChannel lyreChannel) {
        //考虑到重连技术只在客户端使用，并且目前没有并发所以不考虑并发问题
        if (reconnectTask == null) {
            reconnectTask = new Thread(() -> {
                System.out.println("尝试重连任务");
                LyreClient lyreClient = (LyreClient) lyreChannel.getJadeLyre();
                if (lyreClient.isStarted()) {
                    SunPacket sunPacket = SunPacket.encodeBuild("重连的".getBytes());
                    Sun.send(sunPacket, lyreChannel);
//                    lyreClient.getWorkerFactory().getScheduleWorker().schedule(reconnectTask,5, TimeUnit.SECONDS);
                } else {
                    //lyreClient.reconnect(lyreChannel);
                    lyreClient.connect();
                }
            });
        }
        return reconnectTask;
    }
}
